package com.xiangwushuo.framework.activity.main.fragment.home

import android.Manifest
import com.lib.common.base.mvvm.CommonViewModelFragment
import com.lib.common.constant.INTENT_KEY_PARAM1
import com.lib.common.constant.INTENT_KEY_PARAM2
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import com.lib.framework.entity.Event
import com.lib.framework.manager.LogManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.gyf.immersionbar.ImmersionBar
import com.lib.common.api.ApiService
import com.lib.common.entity.api.resp.GetData02Resp
import com.lib.common.helper.api.ApiHelper
import com.lib.common.helper.api.ComRequestCallback
import com.lib.common.helper.api.DomainConfig
import com.lib.common.utils.ComUtils
import com.lib.common.utils.ImageLoadUtil
import com.lib.framework.ext.startActivity
import com.lib.framework.helper.permission.PermissionHelper
import com.lib.framework.widget.ToastUtil
import com.lib.framework.widget.WidgetUtil

import com.xiangwushuo.framework.R
import com.xiangwushuo.framework.activity.web.WebActivity
import com.xiangwushuo.framework.databinding.FragmentHomeBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * Copyright (C), 2019-2020
 * FileName: HomeFragment
 * Author:
 * Date: 2020-01-01 00:00
 * Description: 首页 fragment
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class HomeFragment : CommonViewModelFragment<HomeViewModel>() {

    companion object {

        /**
         * 发给 fragment 的事件
         */
        const val EVENT_XXX = 1 // XXX 事件

        /**
         * 发送给 activity 的事件，activtiy 需要实现 SendEventToActivityListener 接口
         */
        const val FRAGMENT_EVENT_XXXX = 1 // XXXX事件

        @JvmStatic
        fun newInstance(param1: String, param2: String) = HomeFragment().apply {
            arguments = Bundle().apply {
                putString(INTENT_KEY_PARAM1, param1)
                putString(INTENT_KEY_PARAM2, param2)
            }
        }
    }

    private var mDataBinding: FragmentHomeBinding? = null

    override fun getViewModelClass() = HomeViewModel::class.java

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        if (mDataBinding == null) {
            mDataBinding =
                DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
            mDataBinding?.viewModel = mViewModel
        }
        return mDataBinding?.root
    }

    override fun immersionBarEnabled(): Boolean {
        return true
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        ImmersionBar.with(this)
            .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .init()
    }

    override fun initView() {
        mDataBinding?.let { dataBinding ->
            testApi()
            testImageLoad()
            testWeb()
            testPermission()
            testUrlEnv()
        }
    }

    override fun lazyLoad() {

    }


    /**
     * 测试网络请求
     */
    private fun testApi() {
        mDataBinding?.let { dataBinding ->
            dataBinding.btnTv.setOnClickListener {
                val url =
                    " https://api.seniverse.com/v3/weather/now.json?key=SZzh6hTKTCzQoUNej&location=beijing&language=zh-Hans&unit=c"
                ApiHelper.getService(ApiService::class.java)?.getData02(url)
                    ?.request(object : ComRequestCallback<GetData02Resp>() {
                        override fun onSuccess02(data: GetData02Resp?) {
                            val s = data?.toString()
                            LogManager.e("keanbin", "onResponse s = $s")
                            dataBinding.text.text = "onResponse s = $s"
                        }

                        override fun onFailure(t: Throwable) {
                            LogManager.e("keanbin", "getData", t)
                            dataBinding.text.text = t.toString()
                        }
                    })
            }
        }
    }

    /**
     * 测试图片加载
     */
    private fun testImageLoad() {
        mDataBinding?.let { dataBinding ->
            //            ImageLoadUtil.load(
            //                "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607564053,296714209&fm=15&gp=0.jpg",
            //                dataBinding.image)
            //            ImageLoadUtil.loadCircle(
            //                "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1692294345,484054225&fm=26&gp=0.jpg",
            //                dataBinding.image02)
            //            ImageLoadUtil.loadRound(
            //                "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2125219160,2903048045&fm=26&gp=0.jpg",
            //                dataBinding.image03, 10)

            ImageLoadUtil.load(
                "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=607564053,296714209&fm=15&gp=0.jpg",
                dataBinding.image
            )
            ImageLoadUtil.loadCircle(
                "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1692294345,484054225&fm=26&gp=0.jpg",
                dataBinding.image02
            )
            ImageLoadUtil.loadRound(
                "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2125219160,2903048045&fm=26&gp=0.jpg",
                dataBinding.image03,
                10
            )
        }
    }

    /**
     * 测试 webview
     */
    private fun testWeb() {
        mDataBinding?.let { dataBinding ->
            dataBinding.btnTv02.setOnClickListener {
                startActivity(
                    WebActivity::class.java,
                    WebActivity.getStartActivityBundle("测试", "https://www.baidu.com")
                )
            }
        }
    }

    /**
     * 测试 Permission
     */
    private fun testPermission() {
        mDataBinding?.let { dataBinding ->
            dataBinding.btnTv03.setOnClickListener {
                PermissionHelper.requestPermissions(
                    this,
                    object :
                        PermissionHelper.OnPermissionListener {
                        override fun onGranted() {
                            WidgetUtil.showToast("onGranted")
                        }

                        override fun onDenied() {
                            WidgetUtil.showToast("onDenied")
                        }
                    },
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            }
        }
    }

    /**
     * 测试 api 环境切换
     */
    private fun testUrlEnv() {
        mDataBinding?.let { dataBinding ->
            val text = "UrlEnv = " + DomainConfig.getUrlEnv() + ", sHostBase = ${DomainConfig.sHostBase}, sHostWebUrl = ${DomainConfig.sHostWebUrl}"
            dataBinding.text02.text = text
            dataBinding.btnTv04.setOnClickListener {
                if (DomainConfig.getUrlEnv() == 0) {
                    DomainConfig.setUrlEnv(1)
                } else {
                    DomainConfig.setUrlEnv(0)
                }

                ComUtils.cleanAppCache()
                ComUtils.relaunchApp()
            }
        }
    }

    override fun dealEvent(event: Event?): Boolean {
        // 处理 viewModel 发送过来的事件
        when (event?.code) {
            EVENT_XXX -> {
                val extraObj = event.extraObj
                if (extraObj is String) {
                    LogManager.i(mTag, "XXX 事件 的额外参数 extraObj = $extraObj")
                }
                return true
            }
        }

        return super.dealEvent(event)
    }
}
